<?php

include("dal_mysql.php");
require_once '../includes/netsuite_toolkit/PHPtoolkit.php';

class BAL
{
    public $db;
    public $dbQuery;
    public $ns_client;      //used underscore to avoid naming conflict
    public $params;
    public $totalRecords;
    public $email;
    public $password;
    public $account;
    public $role;

    function  __construct()
    {
        $this->db = new Database();

        $this->loadProperties();

        // create a client object. You can specify the host to send requests to, e.g. live, beta, sandbox. Default is live.
        $this->ns_client = new nsClient( nsHost::live );

        // set request level credentials. (email, password, account#, internal id of role)
        //$this->ns_client->setPassport($email, $password, $account, $role);
        $this->ns_client->setPassport($this->email, $this->password, $this->account, $this->role);
    }

    public function getListNames()
    {
        $this->dbQuery = "SELECT id, list_label, image_url, last_modified
                        FROM lists";

        return $this->db->getResults($this->dbQuery);
    }

    public function setSearchKeyword($queryString)
    {
        $this->params = $this->getQueryStringValues($queryString);

        if($this->params)
        {
            if(isset ($this->params["searchValue"]))
            {
                if(is_array($this->params["searchValue"]) && count($this->params["searchValue"]) > 0)
                {
                    $_SESSION["searchKeyword"] = $this->params["searchValue"][0];
                }
                else
                {
                    $_SESSION["searchKeyword"] = $this->params["searchValue"];
                }
            }
        }
    }

    public function getList($query_string)
    {
        $list = "Inventory";

        $this->params = $this->getQueryStringValues($query_string);

        if($this->params)
        {
            if(isset ($this->params["keyColumn"]) && isset ($this->params["keyValue"]))
            {
                $list = $this->params["keyValue"][0];
            }
        }

        return $list;
    }

    public function getSearchResults($keyword, $list)
    {
        $results_array = array();

        switch($list)
        {
            case "Inventory":
                $results_array = $this->getInventoryResults($keyword);
                break;
            default:
                break;
        }

        return $results_array;
    }

    public function getInventoryResults($query)
    {
        //strip out wild cards
        $query = str_replace("*", "", $query);

        //echo $this->account; exit();
        $itemSearch = new nsComplexObject("ItemSearchBasic");

        // Option 1 - instantiate an nsComplexObject and set fields
	/*
	$itemIdSearchField = new nsComplexObject("SearchStringField");
	$itemIdSearchField->setFields(array("operator" 		=> "anyOf",
											"searchValue"	=> $itemId));

	$itemSearch->setFields(array("itemId" => $itemIdSearchField));
	*/

	// Option 2 - give array of fields and the toolkit will use the directory to create
	// a nsComplexObject of type SearchStringField
	$itemSearch->setFields(array("itemId" => array(	"operator" => "contains",	
                                                        "searchValue" => $query)));
	// Both options produce the same soap

	// Set search preferences
	$this->ns_client->setSearchPreferences(false, 50);

	// Invoke search operation
	$searchResponse = $this->ns_client->search($itemSearch);

	if (!$searchResponse->isSuccess)
        {
            $this->totalRecords = 0;
        }
        else
        {
            $this->totalRecords = $searchResponse->totalRecords;
        }

        return $searchResponse->recordList;
    }

    public function getSearchKeyword($queryString)
    {
        $searchKeyword = "";

        $this->params = $this->getQueryStringValues($queryString);

        if($this->params)
        {
            if(isset ($this->params["searchValue"]))
            {
                if(is_array($this->params["searchValue"]) && count($this->params["searchValue"]) > 0)
                {
                    $searchKeyword = $this->params["searchValue"][0];
                }
                else
                {
                    $searchKeyword = $this->params["searchValue"];
                }
            }
        }

        return $searchKeyword;
    }

    public function getQueryStringValues($query_string)
    {
        $query  = explode('&', $query_string);
        $params = array();

        foreach( $query as $param )
        {
            list($name, $value) = explode('=', $param);
            $params[urldecode($name)][] = urldecode($value);
        }

        return $params;
    }

    public function getCountAtCurrentLevel()
    {
        return count($this->db->getResultsWithoutLimit($this->dbQuery));
    }

    public function checkCredentials($email, $password, $account, $role = 3)
    {
        $loginResponse = $this->ns_client->login($email, $password, $account, $role);

        if($loginResponse->isSuccess)
        {
            $this->setProperties($email, $password, $account, $role);

            $this->ns_client->logout();

            return 1;
        }

        return 0;
    }

    public function setProperties($email, $password, $account, $role)
    {
        if (file_exists("includes/custom"))
        {
            $filePath="includes/custom/";
        }
        else if (file_exists("../includes/custom"))
        {
            $filePath="../includes/custom/";
        }

        $fp = fopen($filePath."login.properties", "w") or die ("Could not open ".$filePath."login.properties file");

        fwrite($fp, "Email=" . $email);
        fwrite($fp, "\nPassword=" . $password);
        fwrite($fp, "\nAccount=" . $account);
        fwrite($fp, "\nRole=" . $role);

        fclose($fp);
    }

    private function loadProperties()
    {
        if (file_exists("includes/custom"))
        {
            $filePath="includes/custom/";
        }
        else if (file_exists("../includes/custom"))
        {
            $filePath="../includes/custom/";
        }

        $fp = fopen($filePath."login.properties", "r") or die ("Could not open ".$filePath."login.properties file");

        // iterate through all the lines
	while ($line = fgets($fp))
	{
            // getting the value of the property
            $valueIndex = stripos($line, "=");
            $value = substr($line, $valueIndex +1);


            if (strpos($line, "Email") !== false)
            {
                // if the current line contains 'email' then this value is for 'email'
		$this->email = trim($value);
            }
            elseif (strpos($line, "Password") !== false)
            {
                // if the current line contains 'password' then this value is for 'password'
		$this->password = trim($value);
            }
            elseif (stripos($line, "Account") !== false)
            {
                // if the current line contains 'account' then this value is for 'account'
		$this->account = trim($value);
            }
            elseif (stripos($line, "Role") !== false)
            {
                // if the current line contains 'role' then this value is for 'role'
		$this->role = trim($value);
            }
       	}

	fclose($fp);
    }
}
?>
